//
//  subPageView.swift
//  4444444
//
//  Created by wangyong的MAC on 2021/9/7.
//

import SwiftUI
import Combine
struct subPageView: View {
    @Binding var goal: Int;
    var disposeBag = DisposeBag()
    @Preference(\.shouldShowHelloWorld) var shouldShowHelloWorld
    var other = otherInstance()
    var body: some View {
        VStack{
            VStack {
                Section(header: Text("subMinutesGoal")) {
                    Stepper(value: $goal, in: 150...900, step: 10) {
                        Text("\(goal) subMinutesGoalValue")
                    }
                }
            VStack {
                    Text(shouldShowHelloWorld ? "Hello, world!" : "")
                        .padding()
                    Button("Change text") {
                        shouldShowHelloWorld.toggle()
                    }
                    Toggle("Change text", isOn: $shouldShowHelloWorld)
                    Button("能监听其他实例的改变") {
                          Preferences.standard
                              .preferencesChangedSubject
                              .filter { changedKeyPath in
                                  changedKeyPath == \Preferences.shouldShowHelloWorld
                              }.sink (receiveValue: {  _ in
                                  print("Should show hello world preference changed!")
                              }).add(to: disposeBag)
                          other.shouldShowHelloWorld = true
                   }
                }
        }
        }
    }
}
struct otherInstance {
    @Preference(\.shouldShowHelloWorld) var shouldShowHelloWorld
}
class DisposeBag {
    private var values: [AnyCancellable] = []
    func add(_ value: AnyCancellable) {
        values.append(value)
    }
}
extension AnyCancellable {
    func add(to bag: DisposeBag) {
        bag.add(self)
    }
}
